//
//  XDMeSettingController.m
//  XDEducation
//
//  Created by apple on 2017/4/24.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "XDMeSettingController.h"
#import "XDMeSettingCell.h"
#import "XDHeaderImageCell.h"
#import "XDMeSettingCell.h"
#import "XDSingleBtnCell.h"
#import "XDCustomCell.h"
#import "XDLoginViewController.h"
#import "AppDelegate.h"
#import "XDUpdatePwdView.h"
@interface XDMeSettingController ()<UIAlertViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>

/** 头像 */
@property(nonatomic,strong) UIImageView *iconImageView;


/** 修改密码视图 */
@property(nonatomic,strong)XDUpdatePwdView *updatePwdView;
@end

static NSString *headerImageCellId = @"HeaderImageCell";
static NSString *settingCellId = @"SettingCell";
static NSString *customCellId = @"CustomCell";
static CGFloat headerCellHeiht = 100;

@implementation XDMeSettingController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"个人资料";

    self.tableView.backgroundColor = [UIColor whiteColor];
    
    if([[[UIDevice currentDevice] systemVersion] floatValue]>=8.0) {
        
        self.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    }
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return 5;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 0 || indexPath.row == 4) return headerCellHeiht * ScaleHeight;
    return 50 * ScaleHeight;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //WeakSelf(weakself)
    switch (indexPath.row) {
        case 0:{    //头像
            [tableView registerNib:[UINib nibWithNibName:@"XDHeaderImageCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:headerImageCellId];
            
            XDHeaderImageCell *cell = [tableView dequeueReusableCellWithIdentifier:headerImageCellId];
            NSString *url = [AccountTool shareAccountTool].currentAccount.headImageUrl;
            NSString *iconUrl = BaseIconUrl(url);
            [cell.headImageView sd_setImageWithURL:[NSURL URLWithString:iconUrl] placeholderImage:[UIImage imageNamed:@"mine_bnt_user_default"]];
            cell.headImageView.layer.masksToBounds = YES;
            cell.headImageView.layer.cornerRadius = (headerCellHeiht * ScaleHeight - 20)/2;
            self.iconImageView = cell.headImageView;
            return cell;
        }
            break;
        case 1:{    //用户名
            [tableView registerNib:[UINib nibWithNibName:@"XDMeSettingCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:settingCellId];
            XDMeSettingCell *cell = [tableView dequeueReusableCellWithIdentifier:settingCellId];
            cell.titleLabel.text = @"用户名";
            cell.subtitleLabel.text = [AccountTool shareAccountTool].currentAccount.username;
            return cell;
        }
            break;
        case 2:{    //地区
            [tableView registerNib:[UINib nibWithNibName:@"XDMeSettingCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:settingCellId];
            XDMeSettingCell *cell = [tableView dequeueReusableCellWithIdentifier:settingCellId];
            cell.titleLabel.text = @"地区信息";
            cell.subtitleLabel.text = [AccountTool shareAccountTool].currentAccount.area;
            return cell;
        }
            break;
        case 3:{    //修改密码
            [tableView registerNib:[UINib nibWithNibName:@"XDCustomCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:customCellId];
            XDCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:customCellId];
            return cell;
        }
            break;
        case 4:{
            XDSingleBtnCell *exitBtnCell = [XDSingleBtnCell cellWithTableView:tableView];
            exitBtnCell.title = @"退出登录";
            exitBtnCell.buttonClickedBlock = ^{
            
                UIAlertView *alert= [[UIAlertView alloc]initWithTitle:nil message:@"确定退出登录?" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
                
                [alert show];
            };
            exitBtnCell.separatorInset = UIEdgeInsetsMake(0, ScreenW, 0, 0);
            return exitBtnCell;
        }
            break;
        default:{
            return nil;
        }
            break;
    }
}

//cell点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    switch (indexPath.row) {
        case 0:{        //修改头像
            
            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
            //按钮：拍照
            [alert addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
                imagePickerController.delegate = self;
                imagePickerController.allowsEditing = YES;
                imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
                imagePickerController.modalPresentationStyle = UIModalPresentationOverCurrentContext;
                [self presentViewController:imagePickerController animated:YES completion:nil];
                
                
            }]];
        
            //按钮：从相册选择，
            [alert addAction:[UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                //初始化UIImagePickerController
                UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
                //获取方式1：通过相册（呈现全部相册），UIImagePickerControllerSourceTypePhotoLibrary
                //获取方式2，通过相机，UIImagePickerControllerSourceTypeCamera
                //获取方方式3，通过相册（呈现全部图片），UIImagePickerControllerSourceTypeSavedPhotosAlbum
                PickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;//方式1
                //允许编辑，即放大裁剪
                PickerImage.allowsEditing = YES;
                PickerImage.delegate = self;
                //页面跳转
                [self presentViewController:PickerImage animated:YES completion:nil];
                
            }]];
            //按钮：取消，类型：UIAlertActionStyleCancel
            [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
            [self presentViewController:alert animated:YES completion:nil];
        }
            
            break;
//        case 1:
//            
//            break;
        case 2:      //地区信息
            
            break;
        case 3:{     //修改密码
            
            
            _updatePwdView = [[XDUpdatePwdView alloc]initWithFrame:CGRectMake(0, 0 , ScreenW - 40, 300)];
            _updatePwdView.center =  CGPointMake(self.view.center.x, self.view.center.y - 64);
            WeakSelf(weakself)
            _updatePwdView.sureUpdatePwdBlock = ^(NSString *_oldpwd ,NSString *_newpwd ,NSString *_newpwdAgain){
                
                if (_oldpwd.length < 6 || _newpwdAgain.length < 6 || _newpwd.length < 6) {
                    [MBProgressHUD showError:@"密码格式错误"];
                    return ;
                }
                if(![_newpwd isEqualToString:_newpwdAgain]){
                    [MBProgressHUD showError:@"两次输入的密码不一致"];
                    return;
                }
                [weakself updatePwdNetWorkOldpwd:_oldpwd newpwd:_newpwd];
            };
            
            [_updatePwdView show];
        }
            break;
        default:
            break;
    }
}

//头像图片选择完
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{

    //给相片指定本地路径
    NSString* documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *imagePath = [documentPath stringByAppendingPathComponent:@"123.png"];
    
    
    UIImage *newPhoto = [info objectForKey:@"UIImagePickerControllerEditedImage"];
    //把newPhono设置成头像
    _iconImageView.image = newPhoto;
    
    //保存本地
    NSData *imageData = UIImageJPEGRepresentation(newPhoto, 0.5);
    //保存到document
    [imageData writeToFile:imagePath atomically:YES];
    
    //关闭当前界面，即回到主界面去
    [self dismissViewControllerAnimated:YES completion:nil];
    
    //上传照片
    [self uploadIconImageWithUrl:imagePath];
}


//再次确定退出登录
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (buttonIndex == 0) {     //确定退出登录
        
        [[AccountTool shareAccountTool] removeAccount];
        XDLoginViewController *vc = [[XDLoginViewController alloc]init];
        AppDelegate* appDelagete = (AppDelegate*)[UIApplication sharedApplication].delegate;
        appDelagete.window.rootViewController = vc;
       
        CATransition *animation = [CATransition animation];
        [animation setDuration:0.8];//设置动画时间
        animation.type = kCATransitionFade;//设置动画类型
        [[UIApplication sharedApplication].keyWindow.layer addAnimation:animation forKey:nil];
        
    }
}



#pragma mark - 网络请求

/**
 上传头像
 */
-(void)uploadIconImageWithUrl:(NSString *)imagePath{
    
    NSString *url = BaseURL(@"upload.do?action=uploadHeaderImage");
    NSDictionary *dict = @{@"uid":[AccountTool shareAccountTool].currentAccount.uid};
    
#warning 修改的头像 和用户登录时的头像 不是同一个  需要另外掉接口获取用户头像
    [MBProgressHUD showHUD];
    [XDHttpTool uploadImage:url imageFilePath:imagePath authCode:[AccountTool shareAccountTool].currentAccount.authCode params:dict success:^(id responseObj) {
        
        //NSLog(@"---%@",responseObj);
        [MBProgressHUD showSuccess:@"修改成功"];
        [MBProgressHUD hideHUD];
        
    } failure:^(NSError *error) {
        
        [MBProgressHUD hideHUD];
        NSLog(@"%@",error);
    }];
    
}



/**
 修改密码

 @param oldpwd 旧密码
 @param newpwd 新密码
 */
-(void)updatePwdNetWorkOldpwd:(NSString *)oldpwd newpwd:(NSString *)newpwd{
    
    
    //奇葩的接口 - -  不需要旧密码
    NSString *url = BaseURL(@"user.do?action=setPwd");
    
    NSDictionary *dict = @{@"uid":[AccountTool shareAccountTool].currentAccount.uid,
                           @"pwd":newpwd};
    [MBProgressHUD showHUD];
    [XDHttpTool post:url params:dict success:^(id responseObj) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showSuccess:@"修改成功"];
        NSLog(@"%@",responseObj);
        [_updatePwdView hide];
        
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showError:XDNetWorkError];
        NSLog(@"%@",error);
    }];
    
}

@end
